package com.example.cardgame

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import com.example.cardgame.databinding.ActivityCardGameBinding
import com.example.cardgame.model.CardMatchingGame

class CardGameActivity : AppCompatActivity(), View.OnClickListener {
    private val binding by lazy {ActivityCardGameBinding.inflate(layoutInflater) }
    lateinit var game: CardMatchingGame
    var cardButtons = mutableListOf<Button>()
    var score = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        for (v in binding.gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        game = CardMatchingGame(cardButtons.count())
        updateUI()

        binding.buttonReset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            scoreCallback()
            updateUI()
        }

        binding.buttonExit.setOnClickListener {
            scoreCallback()
            finish()
        }
    }

    fun scoreCallback() {
        score = game.score
        val intent = Intent(this, MainActivity::class.java)
        intent.putExtra(KEY_SCORE, score)
        startActivity(intent)
    }

    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.GRAY)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.cover)
            }
        }
        binding.textScore.text = String.format("%s%d", getString(R.string.score_prefix), game.score)
    }

    override fun onClick(v: View?) {
        if(v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }

}